from ERP_system.utils.get_inventory import Get_inventory
from goods_info.models import *
from rest_framework.serializers import ModelSerializer
from rest_framework import serializers

from goods_info.serializer.units_serializer import UnitsSerializer
from goods_info.serializer.category_serializer import CategorySerializer
from goods_info.serializer.attachment_serializer import AttachmentsSerializer

class GoodsInventorySerializer(serializers.ModelSerializer):
    """
    商品的库存 序列化器
    """

    class Meta:
        model = GoodsInventoryModel
        fields = '__all__'


class GoodsBaseSerializer(serializers.ModelSerializer):
    """
    商品新增，修改，的序列化器

    """

    inventory_list=GoodsInventorySerializer(many=True,required=True)
    class Meta:
        model = GoodsModel
        fields = '__all__'
    def create(self, validated_data):
        #新增商品库存对象的列表
        item_list=validated_data.pop('inventory_list')
        #插入商品信息，生成id
        goods=GoodsModel.objects.create(**validated_data)
        for item in item_list:
            item['cur_inventory']=item.get('init_inventory',0)
            GoodsInventoryModel.objects.create(goods=goods,**item)

        return goods



    def update(self, instance, validated_data):
        item_list = validated_data.pop('inventory_list')


        for item in item_list:  # 遍历每条库存信息，并修改最高库存和最低库存
            GoodsInventoryModel.objects.filter(warehouse_name=item['warehouse_name']).update(
                lowest_inventory=item.get('lowest_inventory', 0), highest_inventory=item.get('highest_inventory', 0))
        goods = super(GoodsBaseSerializer, self).update(instance=instance, validated_data=validated_data)
        return goods


class GoodsGetSerializer(ModelSerializer):
    '''

    商品查询的序列化器
    1. 把商品对应的单位所有内容查询出来
    2. 展示商品信息的所属商品类别-所有信息展示出来
    3.展示商品的所有附件图片-所有信息展示出来
    4.展示商品的所有库存信息

    '''

    #把商品对应的单位所有内容查询出来,进行序列化嵌套
    units=UnitsSerializer(read_only=True)
    #展示商品信息的所属商品类别-所有信息展示出来
    category=CategorySerializer(read_only=True)
    #展示商品的所有附件图片-所有信息展示出来
    images_list=serializers.SerializerMethodField(read_only=True)
    #商品的总库存数量
    cur_inventory=serializers.SerializerMethodField(read_only=True)
    #展示商品的所有库存信息
    inventory_list = GoodsInventorySerializer(many=True, read_only=True)
    class Meta:
        model = GoodsModel
        fields = '__all__'

    def get_images_list(self,obj):
        result=[]
        if obj.images_list:
           ids=obj.images_list.split(',')
           if ids:
                for i in ids:
                    image=AttachmentModel.objects.get(id=int(i))
                    result.append(AttachmentsSerializer(instance=image).data)


        return result

    def get_cur_inventory(self, obj):
        return Get_inventory(obj.id)








